package com.xian.mongo;

import com.mongodb.*;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;

import java.util.*;

public class MyMongoTest {
    public static void main(String[] args) {

    }

    /**
     * 无密码连接
     */
    @Test
    public void getCon(){
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        System.out.println(mongoClient);
        //验证
        MongoDatabase personsDB = mongoClient.getDatabase("xian");
        MongoIterable<String> iterable = personsDB.listCollectionNames();
        MongoCursor<String> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            System.out.println(s);
        }
    }

    /**
     * 无密码连接
     */
    @Test
    public void getCon2(){
        // 连接到 mongodb 服务  mongo 172.18.5.200:20017
        MongoClient mongoClient = new MongoClient( "172.18.5.200" , 20017 );
        System.out.println(mongoClient);
        //验证
        MongoDatabase personsDB = mongoClient.getDatabase("test1");
        MongoIterable<String> iterable = personsDB.listCollectionNames();
        MongoCursor<String> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            System.out.println(s);
        }
    }

    /**
     * 密码连接
     */
    @Test
    public void getCon3(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象


        System.out.println(mongoClient);
        //验证
        MongoDatabase personsDB = mongoClient.getDatabase("activity");
        MongoIterable<String> iterable = personsDB.listCollectionNames();
        MongoCursor<String> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            System.out.println(s);
        }
    }


    /**
     * 查看有多少个数据库 每个库所有表
     */
    @Test
    public void getDBTable(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //列出所有数据库   一般在其他客户端看不见数据库:admin config
        MongoIterable<String> listDatabaseNames = mongoClient.listDatabaseNames();
        MongoCursor<String> dbIt = listDatabaseNames.iterator();
        while (dbIt.hasNext()){
            String db = dbIt.next();
            System.out.println("数据库:"+db);
        }


        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("activity");
        MongoIterable<String> iterable = personsDB.listCollectionNames();
        MongoCursor<String> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            System.out.println(s);
        }



    }


    /**
     * 获取表数据
     */
    @Test
    public void getData(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("carorder");


        MongoCollection<Document> collection = personsDB.getCollection("order_test");

        long countDocuments = collection.countDocuments();
        System.out.println("总数据:"+countDocuments);

        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> iterator = findIterable.iterator();
        while ( iterator.hasNext() ) {
            Document doc = iterator.next();
            for (Map.Entry<String, Object> entry : doc.entrySet()) {
                System.out.print(entry.getKey() + "==" + entry.getValue() + ", ");
            }
            System.out.println();
        }


        mongoClient.close();


        System.out.println("查询完毕!");



    }

    //创建数据库
    @Test
    public void getCreateDB(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println("mongoClient Info => "+mongoClient); //验证是否连接成功

        MongoDatabase testDB = mongoClient.getDatabase("test2"); //相当于切换库
        testDB.createCollection("t_tmp"); //当必须新建一个表，上面的库才会创建成功


        System.out.println("操作完毕!");



    }

    //在现有数据库创建表
    @Test
    public void getCreateTable(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println("mongoClient Info => "+mongoClient); //验证是否连接成功

        MongoDatabase testDB = mongoClient.getDatabase("test2"); //相当于切换库
        testDB.createCollection("t1"); //当必须新建一个表，上面的库才会创建成功


        System.out.println("操作完毕!");



    }

    //查询某个表总行数(文档数)
    @Test
    public void getRowSum(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");


        MongoCollection<Document> collection = personsDB.getCollection("t3");

        long rowSum = collection.countDocuments(); //总行数
        System.out.println("rowSum="+rowSum);


        System.out.println("操作完毕!");



    }


    //增
    @Test
    public void getADD(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");


        MongoCollection<Document> collection = personsDB.getCollection("t1");

        //可以执行一百次，但除了"_id": ObjectId("5f92745f5273845180ce26a3")字段不同，其他内容都是相同的
        Document doc = new Document();
        doc.append("name","詹姆斯");
        doc.append("gender", "男");
        doc.append("age", "24");
        doc.append("address","广州市天河区");
        doc.append("birthday", new Date());

        collection.insertOne(doc);


        System.out.println("操作完毕!");



    }


    //增 批量
    @Test
    public void getADD2(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");


        MongoCollection<Document> collection = personsDB.getCollection("t1");

        //可以执行一百次，但除了"_id": ObjectId("5f92745f5273845180ce26a3")字段不同，其他内容都是相同的
        Document doc = new Document();
        doc.append("name","乔丹");
        doc.append("gender", "男");
        doc.append("age", "30");
        doc.append("address","美国芝加哥");
        doc.append("birthday", new Date());

        Document doc2 = new Document();
        doc2.append("name","科比");
        doc2.append("gender", "男");
        doc2.append("age", "28");
        doc2.append("address","美国洛杉矶");

        Document doc3 = new Document();
        doc3.append("name","老詹");
        doc3.append("gender", "男");
        doc3.append("age", "26");
        doc3.append("address","美国骑师");

        List<Document> docs = new ArrayList<>();
        docs.add(doc);
        docs.add(doc2);
        docs.add(doc3);


        collection.insertMany(docs);



        System.out.println("操作完毕!");



    }


    //查
    @Test
    public void getFind(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = personsDB.getCollection("t1");


        FindIterable<Document> iterable = collection.find();
        MongoCursor<Document> iterator = iterable.iterator();
        while (iterator.hasNext()){
            Document doc = iterator.next();
            Set<Map.Entry<String, Object>> entries = doc.entrySet();
            for(Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                Object value = entry.getValue();
                System.out.print(key + "=" + value + ",");
            }
            System.out.println();




        }


        System.out.println("操作完毕!");



    }

    //改
    @Test
    public void getUpdata(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = personsDB.getCollection("t1");

        Bson bson = Filters.eq("name","杨幂");


        Document updateDoc = new Document();

        updateDoc.append("name","杨幂");
        updateDoc.append("age","39");
        updateDoc.append("address","beijing");
        Document setDoc = new Document("$set",updateDoc);

        UpdateResult updateResult = collection.updateOne(bson, setDoc); //操作修改



        long matchedCount = updateResult.getMatchedCount();
        long modifiedCount = updateResult.getModifiedCount();
        BsonValue upsertedId = updateResult.getUpsertedId();
        System.out.println(upsertedId);
        boolean b = updateResult.wasAcknowledged();

        System.out.println(updateResult);
        System.out.println(matchedCount + "," + modifiedCount + "," + b);






        System.out.println("操作完毕!");



    }



    /**
     * 更新表(集合)数据
     */
    @Test
    public void updateDocs(){



        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = personsDB.getCollection("t1");


        Document filterDoc = new Document("name","杨幂");

        Bson bson = Filters.eq("name","杨幂");

        Document updateDoc = new Document();
        updateDoc.append("name","杨幂");
        updateDoc.append("age","38");
        updateDoc.append("address","beijing");
        Document setDoc = new Document("$set",updateDoc);

        UpdateResult updateResult = collection.updateOne(bson,
                setDoc);



        long modifiedCount = updateResult.getModifiedCount();
        System.out.println("更新记录数:" +  modifiedCount);


        mongoClient.close();


        System.out.println("查询完毕!");

    }


    //删
    @Test
    public void getDel(){
        // 连接到 mongodb 服务
        MongoCredential credential = MongoCredential.createCredential("appuser", "admin", "0IP6k+ERm39lTpjsdBkhohY75WMkyB".toCharArray());   //验证对象
        MongoClientOptions options = MongoClientOptions.builder().build();     //连接操作对象
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.18.5.100",20017),credential,options);   //连接对象
        System.out.println(mongoClient); //验证是否连接成功

        //查看某个数据库下所有表
        MongoDatabase personsDB = mongoClient.getDatabase("carorder");


        MongoCollection<Document> collection = personsDB.getCollection("order_test");




        System.out.println("操作完毕!");



    }
}
